<template>
  <div class="record-view">
    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-button type="primary" @click="showCreateDialog">
          <el-icon><Plus /></el-icon>
          {{ $t('workReports.records.toolbar.newRecord') }}
        </el-button>
        <el-button @click="refreshRecords">
          <el-icon><Refresh /></el-icon>
          {{ $t('workReports.records.toolbar.refresh') }}
        </el-button>
      </div>
      <div class="toolbar-right">
        <el-date-picker
          v-model="selectedDate"
          type="date"
          :placeholder="$t('workReports.records.toolbar.selectDate')"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          @change="handleDateChange"
          style="width: 180px; margin-right: 12px;"
        />
        <el-select
          v-model="selectedCategory"
          :placeholder="$t('workReports.records.toolbar.selectCategory')"
          clearable
          @change="handleCategoryChange"
          style="width: 150px; margin-right: 12px;"
        >
          <el-option
            v-for="category in categories"
            :key="category.id"
            :label="category.name"
            :value="category.id"
          >
            <span class="category-option">
              <el-icon :color="category.color">
                <component :is="getCategoryIcon(category.icon)" />
              </el-icon>
              {{ category.name }}
            </span>
          </el-option>
        </el-select>
        <el-select
          v-model="selectedStatus"
          :placeholder="$t('workReports.records.toolbar.selectStatus')"
          clearable
          @change="handleStatusChange"
          style="width: 120px;"
        >
          <el-option
            v-for="status in STATUS_OPTIONS"
            :key="status.value"
            :label="status.label"
            :value="status.value"
          />
        </el-select>
      </div>
    </div>

    <!-- 记录列表 -->
    <div class="record-list">
      <el-card v-if="records.length === 0 && !recordsLoading" class="empty-state">
        <div class="empty-content">
          <el-icon size="64" color="#C0C4CC"><Document /></el-icon>
          <p>{{ $t('workReports.records.emptyState.title') }}</p>
          <el-button type="primary" @click="showCreateDialog">{{ $t('workReports.records.emptyState.createFirst') }}</el-button>
        </div>
      </el-card>

      <div v-else class="record-cards">
        <el-card
          v-for="record in records"
          :key="record.id"
          class="record-card"
          :class="{ 'completed': record.status === 'COMPLETED' }"
        >
          <div class="record-header">
            <div class="record-title">
              <h3>{{ record.title }}</h3>
              <div class="record-meta">
                <el-tag
                  v-if="record.categoryName"
                  :color="record.categoryColor"
                  size="small"
                  effect="light"
                >
                  {{ record.categoryName }}
                </el-tag>
                <el-tag
                  :type="getStatusType(record.status)"
                  size="small"
                >
                  {{ record.statusDescription }}
                </el-tag>
                <el-tag
                  :type="getPriorityType(record.priority)"
                  size="small"
                >
                  {{ record.priorityDescription }}
                </el-tag>
              </div>
            </div>
            <div class="record-actions">
              <el-button size="small" @click="editRecord(record)">
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button size="small" type="danger" @click="deleteRecord(record)">
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>

          <div v-if="record.content" class="record-content">
            <p>{{ record.content }}</p>
          </div>

          <div class="record-footer">
            <div class="record-info">
              <span class="record-date">
                <el-icon><Calendar /></el-icon>
                {{ record.date }}
              </span>
              <span v-if="record.timeSpent > 0" class="record-time">
                <el-icon><Clock /></el-icon>
                {{ formatTimeSpent(record.timeSpent) }}
              </span>
            </div>
            <div v-if="record.tags && record.tags.length > 0" class="record-tags">
              <el-tag
                v-for="(tag, index) in record.tags"
                :key="tag"
                size="small"
                :type="getTagType(index)"
                effect="light"
                class="custom-tag"
              >
                <el-icon class="tag-icon"><PriceTag /></el-icon>
                {{ tag }}
              </el-tag>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 分页 -->
      <div v-if="recordsPagination.total > 0" class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="recordsPagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="recordsLoading" class="loading">
      <el-skeleton :rows="3" animated />
    </div>

    <!-- 创建/编辑记录对话框 -->
    <WorkRecordDialog
      v-model="dialogVisible"
      :record="currentRecord"
      :categories="categories"
      @success="handleRecordSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useWorkReportStore } from '@/stores/workReportStore'
import { ElMessageBox, ElMessage } from 'element-plus'
import {
  Plus,
  Refresh,
  Edit,
  Delete,
  Document,
  Calendar,
  Clock,
  Folder,
  PriceTag
} from '@element-plus/icons-vue'
import type { WorkRecord } from '@/types/workReport'
import { STATUS_OPTIONS, PRIORITY_OPTIONS } from '@/types/workReport'
import { formatTimeSpent } from '@/api/workReport'
import WorkRecordDialog from './components/WorkRecordDialog.vue'

const { t } = useI18n()
const workReportStore = useWorkReportStore()

// 响应式数据
const dialogVisible = ref(false)
const currentRecord = ref<WorkRecord | null>(null)
const selectedDate = ref('')
const selectedCategory = ref<number | null>(null)
const selectedStatus = ref('')
const currentPage = ref(1)
const pageSize = ref(20)

// 计算属性
const records = computed(() => workReportStore.records)
const categories = computed(() => workReportStore.categories)
const recordsLoading = computed(() => workReportStore.recordsLoading)
const recordsPagination = computed(() => workReportStore.recordsPagination)

// 监听分页变化
watch([currentPage, pageSize], () => {
  fetchRecords()
})

// 获取记录列表
const fetchRecords = () => {
  const params: any = {
    page: currentPage.value - 1,
    size: pageSize.value
  }
  
  if (selectedDate.value) {
    params.date = selectedDate.value
  }
  if (selectedCategory.value) {
    params.categoryId = selectedCategory.value
  }
  if (selectedStatus.value) {
    params.status = selectedStatus.value
  }
  
  workReportStore.fetchRecords(params)
}

// 刷新记录
const refreshRecords = () => {
  fetchRecords()
}

// 显示创建对话框
const showCreateDialog = () => {
  currentRecord.value = null
  dialogVisible.value = true
}

// 编辑记录
const editRecord = (record: WorkRecord) => {
  currentRecord.value = record
  dialogVisible.value = true
}

// 删除记录
const deleteRecord = async (record: WorkRecord) => {
  try {
    await ElMessageBox.confirm(
      t('workReports.records.deleteConfirm.message', { title: record.title }),
      t('workReports.records.deleteConfirm.title'),
      {
        confirmButtonText: t('workReports.records.deleteConfirm.confirmText'),
        cancelButtonText: t('workReports.records.deleteConfirm.cancelText'),
        type: 'warning'
      }
    )
    
    await workReportStore.deleteRecord(record.id!)
    fetchRecords()
  } catch (error) {
    if (error !== 'cancel') {
      console.error(t('workReports.records.messages.deleteFailed'), error)
    }
  }
}

// 处理记录操作成功
const handleRecordSuccess = () => {
  dialogVisible.value = false
  fetchRecords()
}

// 处理日期变化
const handleDateChange = () => {
  currentPage.value = 1
  fetchRecords()
}

// 处理分类变化
const handleCategoryChange = () => {
  currentPage.value = 1
  fetchRecords()
}

// 处理状态变化
const handleStatusChange = () => {
  currentPage.value = 1
  fetchRecords()
}

// 处理页大小变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

// 处理当前页变化
const handleCurrentChange = (page: number) => {
  currentPage.value = page
}

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    'PENDING': 'info',
    'IN_PROGRESS': 'primary',
    'COMPLETED': 'success',
    'CANCELLED': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取优先级类型
const getPriorityType = (priority: string) => {
  const priorityMap: Record<string, string> = {
    'LOW': 'info',
    'MEDIUM': 'primary',
    'HIGH': 'warning',
    'URGENT': 'danger'
  }
  return priorityMap[priority] || 'primary'
}

// 获取标签类型（为不同标签分配不同颜色）
const getTagType = (index: number) => {
  const tagTypes = ['primary', 'success', 'warning', 'danger', 'info']
  return tagTypes[index % tagTypes.length]
}

// 获取分类图标
const getCategoryIcon = (icon: string) => {
  // 这里可以根据图标名称返回对应的图标组件
  return Folder
}

// 组件挂载时获取数据
onMounted(() => {
  fetchRecords()
  workReportStore.fetchCategories() // 获取分类数据，确保WorkRecordDialog能正常工作
})
</script>

<style scoped lang="scss">
.record-view {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px;
  background: var(--el-bg-color);
  border-radius: 8px;
  border: 1px solid var(--el-border-color-light);

  .toolbar-left {
    display: flex;
    gap: 12px;
  }

  .toolbar-right {
    display: flex;
    align-items: center;
  }
}

.record-list {
  flex: 1;
  overflow: auto;
}

.empty-state {
  .empty-content {
    text-align: center;
    padding: 40px 20px;
    color: var(--el-text-color-regular);

    p {
      margin: 16px 0 24px 0;
      font-size: 16px;
    }
  }
}

.record-cards {
  display: grid;
  gap: 16px;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
}

.record-card {
  transition: all 0.3s ease;
  border: 1px solid var(--el-border-color-light);

  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transform: translateY(-2px);
  }

  &.completed {
    opacity: 0.8;
    background: var(--el-color-success-light-9);
  }

  .record-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 12px;

    .record-title {
      flex: 1;

      h3 {
        margin: 0 0 8px 0;
        font-size: 16px;
        font-weight: 600;
        color: var(--el-text-color-primary);
      }

      .record-meta {
        display: flex;
        gap: 6px;
        flex-wrap: wrap;
      }
    }

    .record-actions {
      display: flex;
      gap: 6px;
    }
  }

  .record-content {
    margin-bottom: 12px;

    p {
      margin: 0;
      color: var(--el-text-color-regular);
      line-height: 1.5;
    }
  }

  .record-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 12px;
    border-top: 1px solid var(--el-border-color-lighter);

    .record-info {
      display: flex;
      gap: 16px;
      font-size: 12px;
      color: var(--el-text-color-regular);

      span {
        display: flex;
        align-items: center;
        gap: 4px;
      }
    }

    .record-tags {
      display: flex;
      gap: 4px;
      flex-wrap: wrap;
    }
  }
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

.loading {
  padding: 20px;
}

.category-option {
  display: flex;
  align-items: center;
  gap: 6px;
}
</style>
